<template>
	<view class="fullPage">
		<map id="map" :scale="scale" :latitude="latitude" :longitude="longitude" :markers="list" :show-location="false"
			@regionchange="dragMap" @markertap="markertap" @click="mapTap" style="width: 100vw;height: 100vh">
			<!-- tab栏切换 -->
			<cover-view class="tab_w flex_a" v-show="!markerInfoShow">
				<block v-for="item in tabList" :key="item.status">
					<cover-view class="flex1 h80 lh80 border-r4 ft30 tac"
						:class="activeTab == item.status ? 'b-primary cf' : ''" @click="tapTab(item.status)">
						{{ item.name }}
					</cover-view>
				</block>
			</cover-view>

			<!-- 左侧的电池规则 -->
			<!-- <cover-view class="aside_l flex_a column" v-show="activeTab == 1 && !markerInfoShow">
				<block v-for="item in batterySpec" :key="item.status">
					<cover-view class="flex1 flex_aj h100 lh100 pw100 ft30 tac" :class="activeBattery == item.status ? 'b-primary cf' : ''" @click="chooseBattery(item.status)">
						{{ item.name }}
					</cover-view>
				</block>
			</cover-view> -->

			<!-- 右侧的功能按钮 -->
			<cover-view class="aside_r" v-show="!markerInfoShow">
				<cover-view class="w120 h120 mb30"></cover-view>
				<cover-view class="flex_aj w120 h120 bf border-r50p border-r50p shadow" @click="reset">
					<cover-image src="/static/ic_sx.png" mode="widthFix" style="width: 70upx;height: 70upx;">
					</cover-image>
				</cover-view>
			</cover-view>

			<!-- 底部tabBar start -->
			<cover-view class="tabBar" v-show="!markerInfoShow">
				<!-- 扫一扫 -->
				<cover-view class="tabBar_scan flex_aj column" @click="scanCode">
					<cover-image src="/static/ic_sys_2x.png" mode="widthFix" style="width: 128upx;height: 128upx;">
					</cover-image>
				</cover-view>

				<cover-view class="tabBar_c flex_sb">
					<cover-view class="flex_a">
						<cover-view class="tabBar_item flex_aj column">
							<cover-view class="barImg_w flex_aj">
								<cover-image src="/static/ic_jk_02.png" mode="widthFix"
									style="width: 40upx;height: 48upx;"></cover-image>
							</cover-view>
							<cover-view class="h50 lh50 ft24 c9">监控</cover-view>
						</cover-view>
						<cover-view class="tabBar_item flex_aj column"
							@click="routerLink({ path: '/pages/admin/device/list', query: { lat: latitude, lng: longitude } })">
							<cover-view class="barImg_w flex_aj">
								<cover-image src="/static/ic_sblb.png" mode="widthFix"
									style="width: 40upx;height: 40upx;"></cover-image>
							</cover-view>
							<cover-view class="h50 lh50 ft24 c9">设备列表</cover-view>
						</cover-view>
					</cover-view>

					<cover-view class="flex_a">
						<cover-view class="tabBar_item flex_aj column"
							@click="routerLink({ path: '/pages/admin/userFault/list' })">
							<cover-view class="barImg_w flex_aj">
								<cover-view class="bar_icon" v-show="faultNum">{{ faultNum }}</cover-view>
								<cover-image src="/static/ic_yhbz.png" mode="widthFix"
									style="width: 36upx;height: 42upx;"></cover-image>
							</cover-view>
							<cover-view class="h50 lh50 ft24 c9">用户报障</cover-view>
						</cover-view>
						<cover-view class="tabBar_item flex_aj column"
							@click="routerLink({ path: '/pages/admin/message/index' })">
							<cover-view class="barImg_w flex_aj">
								<cover-view class="bar_icon" v-show="msgNum">{{ msgNum }}</cover-view>
								<cover-image src="/static/ic_ycxx.png" mode="widthFix"
									style="width: 42upx;height: 42upx;"></cover-image>
							</cover-view>
							<cover-view class="h50 lh50 ft24 c9">异常消息</cover-view>
						</cover-view>
					</cover-view>
				</cover-view>
			</cover-view>
			<!-- 底部tabBar end -->

			<!-- 设备详情 start -->
			<cover-view class="map_c p30 bf border-r1 shadow" v-show="markerInfoShow">
				<!-- 换电 / 换电  -->
				<cover-view>
					<cover-view class="flex">
						<cover-view class="flex1">{{ activeTab == 1 ? '换电柜' : '充电柜' }}编号：{{ markerInfo.device_no }}
						</cover-view>

						<cover-view class="whn green"
							:class="markerInfo.device_status == 1 ? 'green' : markerInfo.device_status == 2 ? 'c9' : markerInfo.device_status == 3 ? 'danger' : 'c3'">
							{{ markerInfo.device_status == 1 ? '运行中' : markerInfo.device_status == 2 ? '离线' : markerInfo.device_status == 3 ? '设备故障' : '--' }}
						</cover-view>
					</cover-view>
					<cover-view class="h70 flex_a">
						<cover-view class="flex1 pr24">{{ markerInfo.device_name }}</cover-view>
						<cover-view class="whn c9" v-if="(markerInfo.distance || 0) / 1000 < 1">
							{{ markerInfo.distance }}m
						</cover-view>
						<cover-view class="whn c9" v-else>{{ (markerInfo.distance / 1000).toFixed(2) }}km</cover-view>
					</cover-view>
					<cover-view class="h50">{{ markerInfo.agentName }}</cover-view>
					<cover-view class="flex mb20 c9">
						<cover-view class="flex_a w60 h40">
							<cover-image src="/static/ic_dw_2x.png" mode="widthFix" style="width: 24upx;height: 28upx;">
							</cover-image>
						</cover-view>
						<cover-view class="flex">{{ markerInfo.address }}</cover-view>
					</cover-view>
					<cover-view class="flex_sb mb30 plr30 ptb20 tac bgf5">
						<cover-view class="flex1">
							<cover-view class="mb10">{{ markerInfo.countMd }}</cover-view>
							<cover-view>满电</cover-view>
						</cover-view>
						<cover-view class="flex1">
							<cover-view class="mb10">{{ markerInfo.countCdz }}</cover-view>
							<cover-view>充电中</cover-view>
						</cover-view>
						<cover-view class="flex1">
							<cover-view class="mb10">{{ markerInfo.countKc }}</cover-view>
							<cover-view>空仓</cover-view>
						</cover-view>
						<cover-view class="flex1">
							<cover-view class="mb10">{{ markerInfo.countFault }}</cover-view>
							<cover-view>故障仓</cover-view>
						</cover-view>
						<cover-view class="flex1">
							<cover-view class="mb10">{{ markerInfo.countNoClose }}</cover-view>
							<cover-view>未关门</cover-view>
						</cover-view>
					</cover-view>

					<cover-view class="flex_sb">
						<cover-view class="flex1 h80 lh80 mr24 border-r6 b-warning tac cf tap" @click="
								routerLink({
									path: '/pages/admin/device/detail',
									query: { type: markerInfo.device_type, deviceId: markerInfo.device_Id, lat: latitude, lng: longitude }
								})
							">
							设备详情
						</cover-view>
						<cover-view class="flex1 h80 lh80 border-r6 b-primary tac cf tap" @click="navigation">立即导航
						</cover-view>
					</cover-view>
				</cover-view>
			</cover-view>
			<!-- 设备详情 end -->
		</map>
	</view>
</template>

<script>
	import {
		deviceList,
		scanGetDetail
	} from '@/api/admin.js'
	import * as markersMock from '@/utils/markers.js'
	import {
		nearbyDevice
	} from '@/api/user.js'
	export default {
		name: 'index',
		data() {
			return {
				activeTab: 3, // 1 换电 3 充电
				tabList: [{
					name: '充电',
					status: 3
				}, {
					name: '换电',
					status: 1
				}], // 头部tab栏
				activeBattery: 48, // 当前选中的电池型号
				batterySpec: [{
					name: 'DC48V',
					status: 48
				}, {
					name: 'DC60V',
					status: 60
				}, {
					name: 'DV72V',
					status: 72
				}], // 电池型号列表
				scale: 14, // 地图缩放比例
				latitude: 23.02067,
				longitude: 113.75179,
				list: [], // 设备列表
				markerInfoShow: false, // 是否显示marker点详情
				markerInfo: {}, // marker点相亲
				faultNum: 0, // 未处理保障数
				msgNum: 0 // 异常消息数
			}
		},
		onLoad(e) {
			// let pi = (3.14159265358979324 * 3000.0) / 180.0;
			// let x = this.longitude - 0.0065;
			// let y = this.latitude - 0.006;
			// let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
			// let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
			// this.longitude = z * Math.cos(theta);
			// this.latitude = z * Math.sin(theta);
			this.getLocation()
			this.mapContext = uni.createMapContext('map')
		},
		onShow() {},
		onHide() {
			this.macno = null
		},
		computed: {
			isLogin() {
				return this.$store.state.user.isLogin
			}
		},
		methods: {
			// 点击tab栏
			tapTab(status) {
				this.markerInfoShow = false
				this.activeTab = status
				this.mapContext.removeMarkers({
					markerIds: this.list.map(item => item.id)
				})
				this.getList()
			},
			// 选择电池规格
			/* chooseBattery(status) {
				this.activeBattery = status
				this.mapContext.removeMarkers({ markerIds: this.list.map(item => item.id) })
				this.getList()
			}, */
			async getLocation() {
				let [a, {
					latitude,
					longitude
				}] = await uni.getLocation({
					type: 'gcj02'
				})
				console.log(latitude)
				console.log(longitude)
				this.latitude = latitude
				this.longitude = longitude
				this.getList()
				// this.markersMock()
			},
			getList() {
				this.mapContext.moveToLocation({
					longitude: this.longitude,
					latitude: this.latitude
				})
				this.list = []
				this.list[0] = {
					id: -1,
					latitude: this.latitude * 1,
					longitude: this.longitude * 1,
					iconPath: '/static/ic_dqdw_2x.png',
					width: 100,
					height: 100
				}
				this.nearbyDevice()
			},
			// 模拟数据
			/* 		markersMock() {
				let markers = []
				markersMock.markers.forEach((item, index) => {
					markers.push({
						id: index,
						latitude: item.lat,
						longitude: item.lng,
						width: 42,
						height: 44,
						iconPath: '/static/ic_pos.png',
						title: '',
						anchor: {
							x: 0.5,
							y: 0.5
						}
					})
				})
				this.list = [...this.list, ...markers]
			}, */
			// 附近设备
			async nearbyDevice() {

				const res = await deviceList({
					type: this.activeTab,
					// voltage: this.activeBattery,
					lat: this.latitude,
					lng: this.longitude,
					pageNum: 1,
					pageSize: 999
				})
				console.log(res)

				this.faultNum = res.params.faultCount || 0
				this.msgNum = res.params.msgCount || 0
				this.list = []
				res.rows.forEach((item, index) => {
					const localInfo = {
						index: index,
						id: item.id,
						title: item.device_name,
						address: item.address,
						distance: item.distance,
						latitude: item.lat * 1,
						longitude: item.lng * 1,
						width: 70,
						height: 70,
						iconPath: '/static/ic_sbdw_2x.png',
						anchor: {
							x: 0.5,
							y: 0.5
						}
					}
					// 因后端传过来的经纬度是百度的，所以要经过转化成腾讯经纬度
					let pi = (3.14159265358979324 * 3000.0) / 180.0;
					let x = localInfo.longitude - 0.0065;
					let y = localInfo.latitude - 0.006;
					let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
					let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
					localInfo.longitude = z * Math.cos(theta);
					localInfo.latitude = z * Math.sin(theta);

					const info = {
						...localInfo,
						...item
					}
					info.device_Id = info.id
					info.id = index + 1
					this.list.push(info)
				})
				// this.markerInfo = this.list[1]
			},
			dragMap(e) {
				// 注意：支付宝小程序 如果缩小或者放大了地图比例尺以后，请在 onRegionChange 函数中重新设置 data 的
				// scale 值，否则会出现拖动地图区域后，重新加载导致地图比例尺又变回缩放前的大小。
				// #ifdef MP-ALIPAY
				console.log(e)
				console.log(e.scale)
				this.scale = e.scale

				this.mapContext.getCenterLocation({
					success: res => {
						console.log(res.longitude)
						console.log(res.latitude)

						this.latitude = res.latitude
						this.longitude = res.longitude
					},
					fail: err => {
						console.log(err)
					}
				})
				// #endif
				console.log('地图被拖动')
				this.markerInfoShow = false
			},
			mapTap() {
				console.log('地图被点击')
				// this.markerInfoShow = false
			},
			markertap(e) {
				console.log(e)
				console.log(this.list)
				if (e.detail.markerId < 0) {
					return false
				}
				this.markerInfo = this.list.find(item => item.id == e.detail.markerId)
				this.markerInfoShow = true
				console.log(this.list.find(item => item.id == e.detail.markerId))
			},
			scanCode() {
				const _self = this

				this.routerLink({}, true, () => {
					uni.scanCode({
						scanType: ['barCode', 'qrCode'],
						success(res) {
							if (res.errMsg == 'scanCode:ok') {
								let deviceNo = ''
								let deviceType = 0
								if (res.scanType == 'QR_CODE') {
									// http://weixin.qq.com/r/test?deviceNo=131211&deviceType=1
									// deviceType设备类型 1:换电柜 2：租车 3：充电柜
									deviceNo = _self.getUrlParam('deviceNo', res.result)
									deviceType = _self.getUrlParam('deviceType', res.result)
								}
								if (deviceNo && (deviceType == 1 || deviceType == 3)) {
									_self.scanGetDetail({
										type: deviceType,
										deviceNo: deviceNo
									})
								} else {
									_self.toast('请扫描正确的二维码')
								}
							}
						},
						fail(err) {
							console.log(err)
						}
					})
				})
			},
			async scanGetDetail(query) {
				const res = await scanGetDetail({
					deviceNo: query.deviceNo
				})

				if (res.code == 200) {
					this.routerLink({
						path: '/pages/admin/device/detail',
						query: {
							type: query.deviceType,
							deviceId: res.data.deviceId,
							lat: this.latitude,
							lng: this.longitude
						}
					})
				} else {
					this.confirm({
						content: res.msg || '操作失败',
						showCancel: false
					})
				}
			},
			// 跳转 设备使用页面
			goUsePage(deviceNo, deviceType) {
				// deviceType设备类型 1:换电柜 2：租车 3：充电柜
				let page = ''
				let query = {
					deviceNo,
					lat: this.latitude,
					lng: this.longitude
				}
				// 换电
				if (deviceType == 1) {
					page = '/pages/user/rentEle/index'
				}
				// 租车
				if (deviceType == 2) {
					page = '/pages/user/rentCar/index'
					query = {
						deviceNo,
						latitude: this.latitude,
						longitude: this.longitude
					}
				}
				// 充电
				if (deviceType == 3) {
					page = '/pages/user/chargeEle/index'
				}
			},

			reset() {
				this.scale = 14
				this.mapContext.moveToLocation({
					latitude: this.latitude,
					longitude: this.longitude
				})

				// this.getLocation()
			},
			// navigation() {
			// 	console.log('markerInfo')
			// 	console.log(this.markerInfo)
			// 	uni.openLocation({
			// 		latitude: this.markerInfo.latitude * 1,
			// 		longitude: this.markerInfo.longitude * 1,
			// 		name: this.markerInfo.device_name,
			// 		address: this.markerInfo.address,
			// 		success: () => {
			// 			this.markerInfoShow = false
			// 		}
			// 	})
			// }
			navigation() {
				console.log('markerInfo')
				console.log(this.markerInfo)
				// let pi = (3.14159265358979324 * 3000.0) / 180.0;
				// let x = this.markerInfo.longitude - 0.0065;
				// let y = this.markerInfo.latitude - 0.006;
				// let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
				// let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
				// this.markerInfo.longitude = z * Math.cos(theta);
				// this.markerInfo.latitude = z * Math.sin(theta);
				uni.openLocation({
					latitude: this.markerInfo.latitude * 1,
					longitude: this.markerInfo.longitude * 1,
					name: this.markerInfo.siteName,
					address: this.markerInfo.address,
					success: () => {
						this.markerInfoShow = false
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	cover-view {
		overflow: auto;
		white-space: normal;
	}

	.tab_w {
		position: fixed;
		top: 30upx;
		left: 26upx;
		width: 698upx;
		height: 100upx;
		padding: 10upx 14upx;
		box-sizing: border-box;
		background-color: #fff;
		border-radius: 50upx;
		overflow: hidden;
		box-shadow: 0px 4px 18px 0px rgba(50, 130, 255, 0.24);
	}

	.aside_l {
		position: fixed;
		bottom: 330upx;
		left: 26upx;
		width: 160upx;
		height: 300upx;
		background: #ffffff;
		box-shadow: 0upx 4upx 18upx 0upx rgba(50, 130, 255, 0.24);
		border-radius: 20upx;
		overflow: hidden;
	}

	.aside_r {
		position: fixed;
		bottom: 360upx;
		right: 26upx;
	}

	// 底部tabbar
	.tabBar {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 210upx;

		.tabBar_scan {
			position: absolute;
			top: 0;
			left: 50%;
			z-index: 2;
			transform: translateX(-50%);
		}

		.tabBar_c {
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 150upx;
			padding: 20upx;
			box-sizing: border-box;
			background: #ffffff;
			box-shadow: 1upx -14upx 20upx 0upx rgba(50, 130, 255, 0.1);
			border-radius: 50upx 50upx 0upx 0upx;

			.tabBar_item {
				// flex: 1;
				width: 140upx;

				.barImg_w {
					position: relative;
					overflow: auto;
					white-space: normal;
					width: 100%;
					height: 60upx;

					.bar_icon {
						position: absolute;
						top: 0;
						right: 0;
						height: 30upx;
						line-height: 30upx;
						padding: 0 10upx;
						border-radius: 20upx;
						background-color: #ff6600;
						color: #fff;
						font-size: 22upx;
					}
				}
			}
		}
	}

	.map_c {
		position: fixed;
		bottom: 60upx;
		left: 30upx;
		width: 690upx;
		box-sizing: border-box;
	}

	.bat_wrap {
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		background-color: rgba($color: #000000, $alpha: 0.4);

		.bat_content {
			width: 600upx;
			min-height: 462upx;
			padding: 40upx 30upx;
			margin-bottom: 30upx;
			background-color: #fff;
			border-radius: 10px;

			.table_th {
				height: 50upx;
				line-height: 50upx;
				background: #deeafd;
			}

			.table_tr {
				height: 60upx;
				line-height: 60upx;
				background: #f7faff;
			}
		}

		.bat_close {
			width: 60upx;
			height: 60upx;

			&:active {
				opacity: 0.8;
			}
		}
	}
</style>
